package com.yjh.server.controller.miniapp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yjh.common.other.BusinessException;
import com.yjh.common.utils.FileUploadUtil;
import com.yjh.pojo.dto.UpdatePswDto;
import com.yjh.pojo.dto.UserDto;
import com.yjh.pojo.entity.User;
import com.yjh.pojo.vo.R;
import com.yjh.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/mini/user")
public class MiniUserController {

    @Autowired
    private UserService userService;
    @Autowired
    private FileUploadUtil fileUploadUtil;

    @GetMapping("/getUserById")
    public R<User> getUserById(@RequestParam("id") Integer id){
        User user = userService.getById(id);
        return R.success(user);
    }

    @PostMapping("/uploadFile")
    public R<String> uploadImg(@RequestParam("file") MultipartFile file)throws IOException {
        System.out.println(file);
        String newFilesUrl = fileUploadUtil.uploadFile(file);

        System.out.println(newFilesUrl);
        return R.success(newFilesUrl);
    }

    @PutMapping("/update")
    public R<String> updateUser(@RequestBody UserDto userDto){
        System.out.println(userDto);
//        userService.updateById()
        if (userDto.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserId,userDto.getUserId());

        User user1 = userService.getOne(wrapper);
        user1.setUsername(userDto.getUsername());
        user1.setAvatar(userDto.getAvatar());
        user1.setPhone(userDto.getPhone());
        user1.setRealname(userDto.getRealname());
        userService.updateById(user1);
        return R.success("更新成功");
    }

    @PutMapping("/updatePsw")
    public R<String> updatePsw(@RequestBody UpdatePswDto updatePswDTO, HttpServletRequest request){
        String userId = (String) request.getAttribute("userId");

        if (userId == null) {
            return R.error("用户未登录或Token无效");
        }

        try {
            userService.updatePsw(updatePswDTO,userId);
            return R.success("密码修改成功");
        } catch (BusinessException e) {
            // 捕获业务异常（如原密码错误、用户不存在等）
            return R.error(e.getMessage());
        } catch (Exception e) {
            return R.error("密码修改失败");
        }
    }
}
